package com.blackholemax.structure;

import java.util.Arrays;

public class MyArray {
    private int[] array;
    private int size;

    public MyArray(int capacity) {
        this.array = new int[capacity];
        this.size = 0;
    }

    /**
     * 插入
     *
     * @param element 插入元素
     * @param index   索引
     * @throws IndexOutOfBoundsException 索引越界异常
     */
    public void insert(int element, int index) throws IndexOutOfBoundsException {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index out of bound");
        }
        if (size >= array.length) {
            resize();
        }
        for (int i = size - 1; i >= index; i--) {
            array[i + 1] = array[i];
        }
        array[index] = element;
        size++;
    }

    /**
     * @param index 删除元素的索引
     * @return 删除元素
     * @throws IndexOutOfBoundsException 索引越界异常
     */
    public int delete(int index) throws IndexOutOfBoundsException {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index out of bound");
        }
        int deletedElement = array[index];
        for (int i = index; i <= size - 1; i++) {
            array[i] = array[i + 1];
        }
        size--;
        return deletedElement;
    }

    /**
     * @param index 删除元素的索引
     * @return 删除元素
     * @throws IndexOutOfBoundsException 索引越界异常
     */
    public int quickDelete(int index) throws IndexOutOfBoundsException {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index out of bound");
        }
        int deletedElement = array[index];
        array[index] = array[size - 1];
        array[size - 1] = 0;
        size--;
        return deletedElement;
    }

    /**
     * 数组扩容
     */
    public void resize() {
        int[] newArray = new int[array.length * 2];
        System.arraycopy(array, 0, newArray, 0, array.length);
        this.array = newArray;
    }

    @Override
    public String toString() {
        return "MyArray: " + Arrays.toString(array);
    }
}
